<template>
  <div class="avatar-container" :style="containerStyle">
    <img 
      class="avatar-image" 
      :src="imgSrc" 
      :style="imgStyle"
      @error="handleError"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import helper from '@/utils/helper';

const props = defineProps({
  // 头像资源，可以是MD5值或完整URL
  src: {
    type: String,
    default: ''
  },
  // 头像大小
  size: {
    type: [Number, String],
    default: 64
  },
  // 形状：circle或square
  shape: {
    type: String,
    default: 'circle'
  },
  // 边框颜色
  borderColor: {
    type: String,
    default: 'transparent'
  },
  // 边框宽度
  borderWidth: {
    type: [Number, String],
    default: 0
  },
  // 默认头像
  defaultSrc: {
    type: String,
    default: 'icon/male.png'
  }
});

const imgSrc = ref('');
const loadError = ref(false);

// 容器样式
const containerStyle = computed(() => {
  const size = getNumberValue(props.size);
  const borderWidth = getNumberValue(props.borderWidth);
  
  return {
    width: `${size}px`,
    height: `${size}px`,
    borderRadius: props.shape === 'circle' ? '50%' : '4px',
    borderWidth: `${borderWidth}px`,
    borderColor: props.borderColor,
    borderStyle: borderWidth > 0 ? 'solid' : 'none'
  };
});

// 图片样式
const imgStyle = computed(() => {
  return {
    borderRadius: props.shape === 'circle' ? '50%' : '4px',
  };
});

// 将字符串或数字转为数字
const getNumberValue = (val: string | number) => {
  return typeof val === 'string' ? parseInt(val) : val;
};

// 更新图片源
const updateImageSrc = (src: string) => {
  loadError.value = false;
  
  if (!src || src === '') {
    imgSrc.value = props.defaultSrc;
    return;
  }
  
  // 检查是否为完整URL
  if (/^https?:\/\//.test(src)) {
    imgSrc.value = src;
  } else if (src === '默认头像') {
    imgSrc.value = props.defaultSrc;
  } else {
    // 否则视为MD5，使用helper获取URL
    try {
      imgSrc.value = helper.toApiUrl(`file/download2?md5=${src}`);
    } catch (error) {
      imgSrc.value = props.defaultSrc;
    }
  }
};

// 处理图片加载错误
const handleError = () => {
  loadError.value = true;
  imgSrc.value = props.defaultSrc;
};

// 监听src变化
watch(() => props.src, (newVal) => {
  updateImageSrc(newVal);
}, { immediate: true });
</script>

<style lang="less" scoped>
.avatar-container {
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  
  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style> 